//
//  KRHomeViewController.m
//  cookBook
//
//  Created by kuroken on 16/1/8.
//  Copyright © 2016年 kuroken. All rights reserved.
//

#define MAS_SHORTHAND

#import "KRHomeViewController.h"
#import <Masonry.h>
#import <PureLayout.h>
#import <MJExtension.h>
#import "MBProgressHUD+KR.h"
#import <SVProgressHUD.h>
#import "KRConst.h"
#import "KRHttpRecipeTool.h"
#import "KRNavigationController.h"
#import "KRRecipeListController.h"
#import "KRAlbumListController.h"
#import "KRReadListController.h"
#import "KRResult.h"
#import "KRAlbumView.h"
#import "KRColumnView.h"
#import "KRAlbumInfoController.h"
#import "KRSearchController.h"
#import "KRCateListController.h"
#import "KRRecipeList.h"
#import "KRHomeDataTool.h"

// 首页高度
CGFloat const contentSizeHeight = 820;

@interface KRCategoryBtn : UIButton
@end
@implementation KRCategoryBtn

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setImage:[UIImage imageNamed:@"assort"] forState:UIControlStateNormal];
        [self setImage:[UIImage imageNamed:@"assort_select"] forState:UIControlStateSelected];
        [self setTitle:@"分类" forState:UIControlStateNormal];

        self.titleLabel.font = [UIFont systemFontOfSize:11];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.imageView.y = 0;
    self.imageView.width = self.width;
    self.imageView.height = self.width;
    
    self.titleLabel.x = 0;
    self.titleLabel.y = self.imageView.height - 7;
    self.titleLabel.width = self.width;
    self.titleLabel.height = self.height - self.imageView.height;
    
}

@end

@interface KRHomeViewController () <UIScrollViewDelegate, KRColumnViewDelegate, KRAlbumViewDelegate>
@property (nonatomic, weak) UIScrollView *scrollView;

@property (nonatomic, weak) UIView *navBarView;
@property (nonatomic, weak) UIView *alphaView;
@property (nonatomic, weak) KRCategoryBtn *categoryBtn;
//@property (nonatomic, weak) UISearchBar *searchBar;
@property (nonatomic, weak) UIButton *searchBtn;
/** 图片播放器视图 */
@property (nonatomic, weak) UIView *recipeListView;

/** 热门专辑视图 */
@property (nonatomic, weak) KRAlbumView *albumView;

/** 精品阅读视图 */
@property (nonatomic, weak) UIView *readListView;

/** 首页数据的模型 */
@property (nonatomic, strong) KRResult *results;

/** 当前请求 */
@property (nonatomic, weak) NSURLSessionDataTask *currentDatatask;
//@property (nonatomic, assign, getter=isError) BOOL error;

@property (nonatomic, weak) UIImageView *noNetImageView;
@property (nonatomic, weak) UILabel *labelView;
@end

@implementation KRHomeViewController

- (UIImageView *)noNetImageView
{
    if (!_noNetImageView) {
        UIImageView *noNetImageView = [[UIImageView alloc] init];
        [noNetImageView setImage:[UIImage imageNamed:@"nonet_default"]];
        noNetImageView.size = noNetImageView.image.size;
        [self.view addSubview:noNetImageView];
        _noNetImageView = noNetImageView;
        
        UILabel *labelView= [[UILabel alloc] init];
        [labelView setTextColor:[UIColor grayColor]];
        [labelView setFont:[UIFont systemFontOfSize:15]];
        [labelView setNumberOfLines:0];
        [labelView setTextAlignment:NSTextAlignmentCenter];
        [labelView setText:@"请求超时\n点击屏幕重新加载\n"];
        
        [self.noNetImageView addSubview:labelView];
        self.labelView = labelView;
        
        [self.noNetImageView makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.view);
        }];
        [self.labelView makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.bottom.right.equalTo(self.noNetImageView);
        }];
    }
    return _noNetImageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [SVProgressHUD setBackgroundColor:[UIColor lightGrayColor]];

    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    [self addScrollView];

    // 读取数据
    [self loadData];
    
    // 自定义顶部导航栏
    [self setupNavBar];
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (!_noNetImageView || _noNetImageView.isHidden) return;
    [self.noNetImageView setHidden:YES];
    [self.scrollView setHidden:NO];
    [self loadData];
}

- (void)addScrollView
{
    // scrollView
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    scrollView.backgroundColor = [UIColor whiteColor];
    // 设置scrollView滚动范围
    scrollView.contentSize = CGSizeMake(0, contentSizeHeight);
    scrollView.delegate = self;

    [self.view addSubview:scrollView];
    self.scrollView = scrollView;
    [scrollView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];

    scrollView.contentSize = CGSizeMake(0, contentSizeHeight);

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navBarView.userInteractionEnabled = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navBarView.userInteractionEnabled = NO;
}

/**
 *  向服务器发送请求，读取首页数据
 */
- (void)loadData
{
    [MBProgressHUD showInView:self.scrollView text:@"正在加载中..."];
    
    self.scrollView.scrollEnabled = NO;
    self.scrollView.userInteractionEnabled = NO;
    
    self.currentDatatask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRIndex;
    } success:^(NSURLSessionDataTask *task, id json) {
        if (self.currentDatatask != task) return;
        
        // 缓存
        [KRHomeDataTool saveHomeData:json[@"result"]];
        
        // 将首页数据字典转为模型
        self.results = [KRResult mj_objectWithKeyValues:json[@"result"]];
        
        // 初始化首页
        [self setupHomePage];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.currentDatatask != task) return;
        
        if (error.code == NSURLErrorNotConnectedToInternet) {
            
        }
        
        // 加载数据库中的首页数据
        NSDictionary *results = [KRHomeDataTool results];
        if (results) { // 数据库中有缓存数据
            self.results = [KRResult mj_objectWithKeyValues:results];
            
            // 初始化首页
            [self setupHomePage];
            
        } else {
            [MBProgressHUD hideHUDForView:self.scrollView animated:YES];
            [self.scrollView setHidden:YES];
            [self.noNetImageView setHidden:NO];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:@"网络繁忙！"];
            });
            KRLog(@"%@, %@", self, error);
        }
    }];
}

/*
 * 初始化首页
 */
- (void)setupHomePage
{
    self.scrollView.scrollEnabled = YES;
    // 移除指示器
    [MBProgressHUD hideHUDForView:self.scrollView animated:YES];
    self.scrollView.userInteractionEnabled = YES;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 显示顶部搜索框
        self.navBarView.hidden = NO;
        
        
        // 初始化图片播放器,传递模型数据
        [self setupRecipeList];
        
        // 初始化热门专辑
        [self setupAlbumList];
        
        // 初始化精品阅读
        [self setupReadList];
        
    });

}

/**
 *  初始化精品阅读
 */
- (void)setupReadList
{
    // 栏目标题
    KRColumnView *readColumnView = [[KRColumnView alloc] init];
    // 设置标题名
    [readColumnView setTitle:self.results.read_name];
    // 设置栏目类型
    [readColumnView setColumnType:KRColumnTypeRead];
    // 成为该栏目的代理
    readColumnView.delegate = self;
    [self.scrollView addSubview:readColumnView];

    if (iOS8) { // 添加约束
        [readColumnView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.albumView];
        [readColumnView autoPinEdgeToSuperviewEdge:ALEdgeLeft];
        [readColumnView autoSetDimensionsToSize:CGSizeMake(KRColumnViewWidth, KRColumnViewHeight)];
    } else if (iOS7) {
        readColumnView.frame = CGRectMake(0, CGRectGetMaxY(self.albumView.frame), KRColumnViewWidth, KRColumnViewHeight);
    }
    
    // KRReadListController
    KRReadListController *readListVc = [[KRReadListController alloc] init];
    
    // 成为self的子控制器
    [self addChildViewController:readListVc];
    [self.scrollView addSubview:readListVc.view];
    
    // 设置模型数据
    readListVc.readList = self.results.read_list;
    
    self.readListView = readListVc.view;
    
    if (iOS8) { // 添加约束
        [self.readListView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:readColumnView];
        [self.readListView autoPinEdgeToSuperviewEdge:ALEdgeLeft];
        [self.readListView autoSetDimensionsToSize:CGSizeMake(KRReadListWidth, baseCellHeight * self.results.read_list.count)];
    } else if (iOS7) {
        self.readListView.frame = CGRectMake(0, CGRectGetMaxY(readColumnView.frame), KRReadListWidth, baseCellHeight * self.results.read_list.count);
    }
}

/**
 *  初始化热门专辑
 */
- (void)setupAlbumList
{
    // 栏目标题
    KRColumnView *albumColumnView = [[KRColumnView alloc] init];
    // 设置标题名
    [albumColumnView setTitle:self.results.album_name];
    // 设置栏目类型
    [albumColumnView setColumnType:KRColumnTypeAlbum];
    // 成为该栏目的代理
    albumColumnView.delegate = self;
    [self.scrollView addSubview:albumColumnView];

    if (iOS8) { // 添加约束
        [albumColumnView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.recipeListView];
        [albumColumnView autoPinEdgeToSuperviewEdge:ALEdgeLeft];
        [albumColumnView autoSetDimensionsToSize:CGSizeMake(KRColumnViewWidth, KRColumnViewHeight)];
    } else if (iOS7) {
        albumColumnView.frame = CGRectMake(0, CGRectGetMaxY(self.recipeListView.frame), KRColumnViewWidth, KRColumnViewHeight);
    }
    
    // KRAlbumView
    KRAlbumView *albumView = [[KRAlbumView alloc] init];
    albumView.delegate = self;
    [self.scrollView addSubview:albumView];
    
    // 设置模型数据
    albumView.albumList = self.results.album_list;
    
    if (iOS8) { // 添加约束
        [albumView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:albumColumnView];
        [albumView autoPinEdgeToSuperviewEdge:ALEdgeLeft];
        [albumView autoSetDimensionsToSize:CGSizeMake(KRAlbumWidth, KRAlbumHeight - KRColumnViewHeight)];
    } else if (iOS7) {
        albumView.frame = CGRectMake(0, CGRectGetMaxY(albumColumnView.frame), KRAlbumWidth, KRAlbumHeight - KRColumnViewHeight);
    }

    
    self.albumView = albumView;
}

#pragma mark - KRAlbumViewDelegate
- (void)albumViewDidClickAlbumBtn:(UIButton *)btn withAlbumID:(NSString *)albumID
{
    KRAlbumInfoController *infoVc = [[KRAlbumInfoController alloc] init];
    infoVc.albumID = albumID;
    [self.navigationController pushViewController:infoVc animated:YES];
}

#pragma mark - KRColumnViewDelegate
/**
 *  点击更多
 */
- (void)columnView:(KRColumnView *)columnView columnType:(KRColumnType)type
{
    if (type == KRColumnTypeAlbum) {
        KRAlbumListController *albumListVc = [[KRAlbumListController alloc] init];
        // 设置顶部标题
        [albumListVc setTitle:@"专辑"];
        [self.navigationController pushViewController:albumListVc animated:YES];
        
    } else if (type == KRColumnTypeRead) {
        KRReadListController *readListVc = [[KRReadListController alloc] init];
        readListVc.push = YES;
        
        // 设置顶部标题(精品阅读)
        [readListVc setTitle:self.results.read_name];
        [self.navigationController pushViewController:readListVc animated:YES];
    }
    
}

/**
 *  初始化图片播放器  KRRecipeListController
 */
- (void)setupRecipeList
{
    // KRRecipeListController  图片播放器
    KRRecipeListController *recipeListVc = [[KRRecipeListController alloc] init];
    NSMutableArray<KRRecipeList *> *recipeArray = [NSMutableArray arrayWithArray:self.results.recipe_list];
    for (KRRecipeList *recipeList in self.results.recipe_list) {
        
//        KRLog(@"%@", recipeList.url);
//        KRLog(@"%@", recipeList.title);
#warning 过滤商品页
        if ([recipeList.url containsPartString:@"goods"]) {
            [recipeArray removeObject:recipeList];
        }
    }
    
    // 设置模型数据
//    recipeListVc.recipeList = self.results.recipe_list;
    recipeListVc.recipeList = recipeArray;
    
    // 成为self的子控制器
    [self addChildViewController:recipeListVc];
    [self.scrollView addSubview:recipeListVc.view];

    
    self.recipeListView = recipeListVc.view;
    // 添加约束
    if (iOS8) {
        [self.recipeListView autoPinEdgeToSuperviewEdge:ALEdgeTop];
        [self.recipeListView autoPinEdgeToSuperviewEdge:ALEdgeLeft];
        [self.recipeListView autoSetDimensionsToSize:CGSizeMake(KRLayoutWidth, KRLayoutHeight)];
    } else if (iOS7) {
        self.recipeListView.frame = CGRectMake(0, 0, KRLayoutWidth, KRLayoutHeight);
    }

}


/**
 *  自定义顶部导航栏
 */
- (void)setupNavBar
{
    // 添加navBarView
    UIView *navBarView = [[UIView alloc] init];
    navBarView.hidden = YES;
    [navBarView setBackgroundColor:[UIColor clearColor]];
    
#warning 将navBarView添加到navigationControl的view中，并且插入到navigationBar下面
    [self.navigationController.view insertSubview:navBarView belowSubview:self.navigationController.navigationBar];
    
    [navBarView autoPinEdgeToSuperviewEdge:ALEdgeTop];
    [navBarView autoPinEdgeToSuperviewEdge:ALEdgeLeft];
    [navBarView autoPinEdgeToSuperviewEdge:ALEdgeRight];
    [navBarView autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:self.navigationController.navigationBar];
    self.navBarView = navBarView;
    
    // 添加透明度可变的view
    UIView *alphaView = [[UIView alloc] init];
    alphaView.backgroundColor = KRColor(249, 249, 249);
    alphaView.alpha = 0.0;
    [self.navBarView addSubview:alphaView];
    [alphaView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
    self.alphaView = alphaView;
    
    // 添加分类按钮
    KRCategoryBtn *categoryBtn = [[KRCategoryBtn alloc] init];
    [categoryBtn addTarget:self action:@selector(categoryBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navBarView addSubview:categoryBtn];
    [categoryBtn autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:20];
    [categoryBtn autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:10];
    [categoryBtn autoSetDimensionsToSize:CGSizeMake(30, 50)];
    self.categoryBtn = categoryBtn;
    
    // 添加搜索按钮
    UIButton *searchBtn = [[UIButton alloc] init];
    [searchBtn setImage:[UIImage imageNamed:@"homeSearch"] forState:UIControlStateNormal];
    [searchBtn setTitle:@"搜索菜谱、专辑" forState:UIControlStateNormal];
    [searchBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [searchBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [searchBtn setBackgroundColor:[UIColor whiteColor]];
    searchBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    searchBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [searchBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    searchBtn.layer.cornerRadius = 5;
    searchBtn.clipsToBounds = YES;
    [searchBtn addTarget:self action:@selector(searchBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navBarView addSubview:searchBtn];
    [searchBtn autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:10];
    [searchBtn autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:self.categoryBtn withOffset:5];
    [searchBtn autoPinEdge:ALEdgeRight toEdge:ALEdgeLeft ofView:self.categoryBtn withOffset:-10];
    self.searchBtn = searchBtn;

}

/**
 *  点击搜索框按钮
 */
- (void)searchBtnClick
{
    KRSearchController *searchVc = [[KRSearchController alloc] init];
    [self.navigationController pushViewController:searchVc animated:NO];
}

/**
 *  点击分类按钮
 */
- (void)categoryBtnClick
{
    KRCateListController *cateListVc = [[KRCateListController alloc] init];
    [self.navigationController pushViewController:cateListVc animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat alpha = self.scrollView.contentOffset.y * 0.01;
    self.alphaView.alpha = alpha;
    
    if (alpha < 0.0) {
        self.navBarView.alpha = alpha * 3 + 1;
//        KRLog(@"navBarView : %f", self.navBarView.alpha);
    } else {
        self.navBarView.alpha = 1.0;
    }
    self.categoryBtn.selected = alpha > 0.5;
    [self.categoryBtn setTitleColor:alpha < 0.5 ? [UIColor whiteColor]:KRColor(117, 117, 117) forState:UIControlStateNormal];
//    KRLog(@"alphaView : %f", self.alphaView.alpha);

}


@end